package com.nsi.service.Impl;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.nsi.common.ServerResponse;
import com.nsi.dao.SysExceptionLogMapper;
import com.nsi.pojo.SysExceptionLog;
import com.nsi.service.ICommonApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author Li Yan
 * @create 2019-03-13
 **/
@Service
@Slf4j
public class CommonApiServiceImpl implements ICommonApiService {

    @Autowired
    private SysExceptionLogMapper sysExceptionLogMapper;

    /**
     * @param env
     */
    @Override
    public ServerResponse ErrorNotify(String env, String data, String url, String api, String errMsg) {

        SysExceptionLog sysExceptionLog = new SysExceptionLog();
        sysExceptionLog.setApi_url(api);
        sysExceptionLog.setRequest_data(data);
        sysExceptionLog.setErr_msg(errMsg);
        sysExceptionLog.setHtml_url(url);
        sysExceptionLog.setEnv(env);

        int i = sysExceptionLogMapper.insert(sysExceptionLog);

        return ServerResponse.createBySuccess("上传成功");
    }


    // 微信小程序登录（研究院商城）获取openId

    /**
     * @param code
     */
    @Override
    public ServerResponse MiniProgramLogin_shop(String code) {

//      研究院商城小程序 参数
        // 准备请求参数
        String MiniAppid = "wx239dd449dc72d145";
        String secret = "11a452b00b37ddba1a7543c25a8a30dc";
        String js_code = code;
        String grant_type = "authorization_code";
        //	发送请求
        BufferedReader reader = null;
        // 请求返回值
        String strJson = "0";
        int CONNECT_TIMEOUT = 5000;
        String DEFAULT_ENCODING = "UTF-8";

        System.out.println("js_code:" + js_code);
        String urlStr = "https://api.weixin.qq.com/sns/jscode2session?appid=" + MiniAppid + "&secret=" + secret + "&js_code=" + js_code + "&grant_type=" + grant_type + "";
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(CONNECT_TIMEOUT);
//            传入参数
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
            writer.flush();
            writer.close();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\r\n");
            }
            // 返回值
            strJson = sb.toString();
        } catch (IOException e) {
            System.err.println("Payment_api:小程序微信支付：失败");
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
            }
        }
        System.out.println("WechatPaymentUtil: 小程序微信支付：返回strJson:" + strJson);
        JsonObject returnData = new JsonParser().parse(strJson).getAsJsonObject();
        String session_key = returnData.get("session_key").getAsString();
        String openid = returnData.get("openid").getAsString();
        System.out.println("WechatPaymentUtil: 小程序微信支付：session_key:" + session_key + openid);

        return ServerResponse.createBySuccess("上传成功", openid);
    }


    //接口加密-验证加密code
    @Override
    public String[] checkVerityCode(String code) {

        String[] myArray = {"0", "0"};
        // 非空效验
        if (StringUtils.isEmpty(code) || code.length() <= 1) {
            myArray[0] = "1";
            myArray[1] = "code无效";
            return myArray;
        }
//        code拆分
        String codeMsg = code.substring(0, 26);
        String MD5_String = code.substring(26);
//        还原字符替换
        String bb = codeMsg.replace("7", "3").replace("4", "6");
        System.out.println("解密aa：" + codeMsg);
//        System.out.println("解密bb："+bb);
        System.out.println("解密MD5：" + MD5_String);

        System.out.println();
        String NewMD5 = DigestUtils.md5DigestAsHex(bb.getBytes());
        System.out.println("新解密MD5：" + NewMD5);

        if (MD5_String.equals(NewMD5)) {
            myArray[0] = "0";
            myArray[1] = "成功";

//            有效期验证
            String codeTime = codeMsg.substring(13, 26);
            System.out.println("时间验证：" + codeTime);
            System.out.println("时间验证：" + System.currentTimeMillis());
//            有效期
            if (System.currentTimeMillis() - Long.parseLong(codeTime) < 60000) {
                return myArray;
            }
            myArray[0] = "3";
            myArray[1] = "时间戳超时";
            return myArray;

        } else {
            myArray[0] = "2";
            myArray[1] = "MD5验算失败";
            return myArray;
        }

    }

    public static String[] checkVerityCode00(String code) {
        String[] myArray = {"0", "0"};
        // 非空效验
        if (StringUtils.isEmpty(code) || code.length() <= 1) {
            myArray[0] = "1";
            myArray[1] = "code无效";
            return myArray;
        }
//        code拆分
        String codeMsg = code.substring(0, 26);
        String MD5_String = code.substring(26);
//        还原字符替换
        String bb = codeMsg.replace("7", "3").replace("4", "6");
        System.out.println("解密aa：" + codeMsg);
//        System.out.println("解密bb："+bb);
        System.out.println("解密MD5：" + MD5_String);

        System.out.println();
        String NewMD5 = DigestUtils.md5DigestAsHex(bb.getBytes());
        System.out.println("新解密MD5：" + NewMD5);

        if (MD5_String.equals(NewMD5)) {
            myArray[0] = "0";
            myArray[1] = "成功";

//            有效期验证
            String codeTime = codeMsg.substring(13, 26);
            System.out.println("时间验证：" + codeTime);
            System.out.println("时间验证：" + System.currentTimeMillis());
            if (System.currentTimeMillis() - Long.parseLong(codeTime) < 17) {
                return myArray;
            }
            myArray[0] = "3";
            myArray[1] = "时间戳超时";
            return myArray;

        } else {
            myArray[0] = "2";
            myArray[1] = "MD5验算失败";
            return myArray;
        }
    }

}
